const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { body, query, param, validationResult } = require('express-validator');
const { authMiddleware, optionalAuthMiddleware } = require('../middlewares/auth.middleware');
const postController = require('../controllers/post.controller');
const router = express.Router();
const { adminMiddleware } = require('../middlewares/auth.middleware');
const { updatePostStatus } = require('../controllers/post.controller'); // 假设有此控制器方法
const { check } = require('express-validator');

// --- Multer 配置 ---
// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../uploads/posts');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const fileFilter = (req, file, cb) => {
  // 只接受图片文件
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('只允许上传图片文件!'), false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 1024 * 1024 * 5 // 限制文件大小为 5MB
  }
});

// --- 路由定义 ---

// 创建帖子
router.post('/',
  authMiddleware,
  upload.fields([{ name: 'images', maxCount: 9 }]), // 最多上传9张图片
  [
    body('title').trim().isLength({ min: 2, max: 100 }).withMessage('标题长度必须在2-100个字符之间'),
    body('content').trim().isLength({ min: 10 }).withMessage('内容至少需要10个字符'),
    body('tags')
      .optional()
      .custom(value => {
        try {
          // 尝试解析 JSON 字符串
          if (typeof value === 'string') {
            const parsedTags = JSON.parse(value);
            if (!Array.isArray(parsedTags)) {
              throw new Error('标签必须是数组');
            }
            if (parsedTags.length > 5) {
              throw new Error('最多添加5个标签');
            }
            return true;
          }
          // 如果已经是数组
          if (Array.isArray(value)) {
            if (value.length > 5) {
              throw new Error('最多添加5个标签');
            }
            return true;
          }
          throw new Error('标签格式无效');
        } catch (error) {
          throw new Error(error.message || '标签格式无效');
        }
      }),
    body('isDraft').optional().isBoolean().withMessage('isDraft 必须是布尔值')
  ],
  postController.createPost
);

// 获取帖子列表 (社区)
router.get('/',
  [
    query('page').optional().isInt({ min: 1 }).withMessage('page 必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('limit 必须是 1 到 50 之间的整数'),
    query('sort').optional().isIn(['latest', 'popular']).withMessage('无效的排序方式'),
    query('tag').optional().isString().trim().escape(), // 防止 XSS
    query('category').optional().isMongoId().withMessage('分类ID无效')
  ],
  async (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  postController.getPosts
);

// 获取单个帖子详情
router.get('/:id',
  optionalAuthMiddleware, // 允许未登录用户查看公开帖子
  [param('id').isMongoId().withMessage('无效的帖子 ID')],
  async (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  postController.getPostDetails
);

// 更新帖子
router.put('/:id',
  authMiddleware,
  upload.fields([{ name: 'images', maxCount: 9 }]), // 允许更新时上传新图片
  [
    param('id').isMongoId().withMessage('无效的帖子 ID'),
    body('title').optional().trim().isLength({ min: 2, max: 100 }).withMessage('标题长度必须在2-100个字符之间'),
    body('content').optional().trim().isLength({ min: 10 }).withMessage('内容至少需要10个字符'),
    body('tags').optional().isArray().withMessage('标签必须是数组').custom(tags => tags.length <= 5).withMessage('最多添加5个标签'),
    body('isDraft').optional().isBoolean().withMessage('isDraft 必须是布尔值'),
  body('category').isMongoId().withMessage('分类ID无效'),
    body('removedImages').optional().isArray().withMessage('removedImages 必须是数组') // 用于告知后端哪些图片被删除了
        .custom(arr => arr.every(item => typeof item === 'string')).withMessage('removedImages 数组必须只包含字符串URL')
  ],
  postController.updatePost
);

// 删除帖子
router.delete('/:id',
  authMiddleware,
  [param('id').isMongoId().withMessage('无效的帖子 ID')],
  async (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  postController.deletePost
);

// 点赞/取消点赞帖子
router.post('/:id/like',
  authMiddleware,
  [param('id').isMongoId().withMessage('无效的帖子 ID')],
  async (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  postController.likePost
);

// 获取帖子交互状态
router.get('/:id/interaction',
    authMiddleware,
    [param('id').isMongoId().withMessage('无效的帖子 ID')],
    async (req, res, next) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        next();
    },
    postController.getPostInteractionStatus
);

// 获取某个用户的帖子列表 (公开的或自己的草稿)
router.get('/user/:userId',
    optionalAuthMiddleware, 
    [
        param('userId').isMongoId().withMessage('无效的用户 ID'),
        query('page').optional().isInt({ min: 1 }).withMessage('page 必须是正整数'),
        query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('limit 必须是 1 到 50 之间的整数'),
        query('type').optional().isIn(['published', 'drafts']).withMessage('无效的类型')
    ],
    async (req, res, next) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        next();
    },
    postController.getUserPosts
);

// 获取热门话题
router.get('/topics/hot', async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 10

    // 获取最近一周的热门话题
    const oneWeekAgo = new Date()
    oneWeekAgo.setDate(oneWeekAgo.getDate() - 7)

    const hotTopics = await Post.aggregate([
      {
        $match: {
          createdAt: { $gte: oneWeekAgo },
          status: 'published'
        }
      },
      {
        $unwind: '$tags'
      },
      {
        $group: {
          _id: '$tags',
          count: { $sum: 1 },
          posts: { $push: { id: '$_id', title: '$title' } }
        }
      },
      {
        $sort: { count: -1 }
      },
      {
        $limit: limit
      },
      {
        $project: {
          _id: 0,
          tag: '$_id',
          count: 1,
          posts: { $slice: ['$posts', 3] } 
        }
      }
    ])

    res.json(hotTopics)
  } catch (error) {
    console.error('获取热门话题失败:', error)
    res.status(500).json({ error: '获取热门话题失败' })
  }
})

// 管理员更新帖子状态 (审核)
router.patch(
  '/admin/posts/:id/status',
  authMiddleware,
  adminMiddleware,
  [
    body('status', '状态是必需的').notEmpty(),
    body('status', '无效的状态').isIn(['pending', 'approved', 'rejected'])
  ],
  updatePostStatus
);

module.exports = router;